package com.starhub.domain.knowledge.service.impl;

import com.starhub.application.collection.dto.DataDefinitionDto;
import com.starhub.application.collection.dto.DataDefinitionLinkDto;
import com.starhub.application.collection.entity.KnowledgeBase;
import com.starhub.application.collection.entity.KnowledgeCollection;
import com.starhub.application.collection.service.DataDefinitionService;
import com.starhub.application.collection.service.KnowledgeBaseService;
import com.starhub.application.collection.service.KnowledgeCollectionService;
import com.starhub.domain.knowledge.dto.KnowledgeBaseDto;
import com.starhub.domain.knowledge.dto.KnowledgeCollectionDto;
import com.starhub.domain.knowledge.service.KnowledgeSettingService;
import com.starhub.domain.knowledge.vo.KnowledgeBaseVo;
import com.starhub.domain.knowledge.vo.KnowledgeCollectionVo;
import com.starhub.engine.generator.genid.IdGenerator;
import com.starhub.utils.HubBeanUtils;
import com.starhub.utils.Util;

import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 知识库设置服务实现类
 * 
 * @version: V1.0
 * @author: liuhf
 * @time 2025-06-06
 */
@Slf4j
@Service
public class KnowledgeSettingServiceImpl implements KnowledgeSettingService {

    @Autowired
    private KnowledgeBaseService knowledgeBaseService;

    @Autowired
    private KnowledgeCollectionService knowledgeCollectionService;

    @Autowired
    private DataDefinitionService dataDefinitionService;

    /**
     * 创建知识库
     * 
     * @param knowledgeBaseDto 知识库信息
     * @return 是否创建成功
     */
    @Override
    public boolean createKnowledgeBase(KnowledgeBaseDto knowledgeBaseDto) {
        KnowledgeBase knowledgeBase = HubBeanUtils.convert(knowledgeBaseDto, KnowledgeBase.class);
        knowledgeBase.setId(IdGenerator.generateId());
        return knowledgeBaseService.insert(knowledgeBase) > 0;
    }

    /**
     * 更新知识库
     * 
     * @param knowledgeBaseDto 知识库信息
     * @return 是否更新成功
     */
    @Override
    public boolean updateKnowledgeBase(KnowledgeBaseDto knowledgeBaseDto) {
        KnowledgeBase knowledgeBase = HubBeanUtils.convert(knowledgeBaseDto, KnowledgeBase.class);
        return knowledgeBaseService.updateById(knowledgeBase) > 0;
    }

    /**
     * 删除知识库（软删除）
     * 
     * @param id 知识库ID
     * @return 是否删除成功
     */
    @Override
    public boolean deleteKnowledgeBase(Long id) {
        KnowledgeBase knowledgeBase = new KnowledgeBase();
        knowledgeBase.setId(id);
        knowledgeBase.setDeleteType(1);

        // TODO 删除知识库表 + 知识库表关联的集合 + 集合关联的知识条目
        return knowledgeBaseService.updateById(knowledgeBase) > 0;
    }

    /**
     * 创建知识库表
     * 
     * @param knowledgeCollectionDto 知识库表信息
     * @return 是否创建成功
     */
    @Override
    public boolean createKnowledgeCollection(KnowledgeCollectionDto knowledgeCollectionDto) {
        // 1. 参数校验
        if (Util.isEmpty(knowledgeCollectionDto.getName())) {
            throw new IllegalArgumentException("表名不能为空");
        }
        if (Util.isEmpty(knowledgeCollectionDto.getCollectionIdentifier())) {
            throw new IllegalArgumentException("表标识不能为空");
        }
        if (knowledgeCollectionDto.getBaseId() == null) {
            throw new IllegalArgumentException("所属知识库ID不能为空");
        }
        if (knowledgeCollectionDto.getCollectionIdentifier().length() > 20) {
            throw new IllegalArgumentException("表标识长度不能超过20位");
        }
        // 校验表标识唯一性
        if (knowledgeCollectionService.countByIdentifier(knowledgeCollectionDto.getCollectionIdentifier()) > 0) {
            throw new IllegalArgumentException("表标识已存在");
        }
        KnowledgeCollection knowledgeCollection = HubBeanUtils.convert(knowledgeCollectionDto,
                KnowledgeCollection.class);

        // 2. 校验知识库是否存在
        KnowledgeBase knowledgeBase = knowledgeBaseService.selectByIdAndNotDeleted(knowledgeCollection.getBaseId());
        if (knowledgeBase == null) {
            throw new IllegalArgumentException("所属知识库不存在");
        }

        // 3. 表id
        Long collectionId = IdGenerator.generateId();

        // 4. 创建表
        dataDefinitionService.createDataDefinition(
                DataDefinitionDto.builder()
                        .id(knowledgeCollection.getId())
                        .name(knowledgeCollection.getName())
                        .collectionIdentifier(knowledgeCollection.getCollectionIdentifier())
                        .description(knowledgeCollection.getDescription())
                        .businessType(knowledgeCollection.getBusinessType())
                        .metaStorageType(knowledgeCollection.getMetaStorageType())
                        .id(collectionId)
                        .vectorModel(knowledgeBase.getVectorModel())
                        .build());

        // 5. 保存到数据库
        KnowledgeCollection collection = HubBeanUtils.convert(knowledgeCollectionDto, KnowledgeCollection.class);

        collection.setId(collectionId);
        collection.setCreateTime(LocalDateTime.now());
        collection.setUpdateTime(LocalDateTime.now());
        collection.setBusinessType(
                knowledgeCollection.getBusinessType() == null ? 0 : knowledgeCollection.getBusinessType());
        return knowledgeCollectionService.insert(collection) > 0;
    }

    /**
     * 更新知识库表
     * 
     * @param knowledgeCollectionDto 知识库表信息
     * @return 是否更新成功
     * @throws IllegalArgumentException 参数校验失败
     */
    @Override
    public boolean updateKnowledgeCollection(KnowledgeCollectionDto knowledgeCollectionDto) {
        if (knowledgeCollectionDto.getId() == null) {
            throw new IllegalArgumentException("知识库表ID不能为空");
        }

        // 获取原数据
        KnowledgeCollection existingCollection = knowledgeCollectionService.selectById(knowledgeCollectionDto.getId());
        if (existingCollection == null) {
            throw new IllegalArgumentException("知识库表不存在");
        }

        KnowledgeCollection knowledgeCollection = HubBeanUtils.convert(knowledgeCollectionDto,
                KnowledgeCollection.class);

        // TODO dataDefinitionService更新知识库表

        // 只更新允许的字段
        KnowledgeCollection updateCollection = new KnowledgeCollection();
        updateCollection.setId(knowledgeCollection.getId());
        updateCollection.setName(knowledgeCollection.getName());
        updateCollection.setDescription(knowledgeCollection.getDescription());
        updateCollection.setUpdateTime(LocalDateTime.now());
        updateCollection.setCollectionIdentifier(knowledgeCollection.getCollectionIdentifier());
        return knowledgeCollectionService.updateById(updateCollection);
    }

    /**
     * 删除知识库表（软删除）
     * 
     * @param id 知识库表ID
     * @return 是否删除成功
     */
    @Override
    public boolean deleteKnowledgeCollection(Long id) {
        KnowledgeCollection knowledgeCollection = new KnowledgeCollection();
        knowledgeCollection.setId(id);
        knowledgeCollection.setDeleteType(1);
        knowledgeCollection.setUpdateTime(LocalDateTime.now());

        // TODO 删除知识库表 + 知识库表关联的集合 + 集合关联的知识条目
        return knowledgeCollectionService.updateById(knowledgeCollection);
    }

    /**
     * 根据ID获取知识库
     * 
     * @param id 知识库ID
     * @return 知识库信息
     */
    @Override
    public KnowledgeBaseVo getKnowledgeBaseById(Long id) {
        KnowledgeBase knowledgeBase = knowledgeBaseService.selectByIdAndNotDeleted(id);
        KnowledgeBaseVo knowledgeBaseVo = HubBeanUtils.convert(knowledgeBase, KnowledgeBaseVo.class);
        return knowledgeBaseVo;
    }

    /**
     * 根据ID获取知识库表
     * 
     * @param id 知识库表ID
     * @return 知识库表信息
     */
    @Override
    public KnowledgeCollectionVo getKnowledgeCollectionById(Long id) {
        KnowledgeCollection knowledgeCollection = knowledgeCollectionService.selectById(id);
        KnowledgeCollectionVo knowledgeCollectionVo = HubBeanUtils.convert(knowledgeCollection,
                KnowledgeCollectionVo.class);
        return knowledgeCollectionVo;
    }

    /**
     * 添加主数据表和元数据表的关联
     * 
     * @param dataDefinitionLinkDto
     * @return
     */
    @Override
    public boolean addLink(DataDefinitionLinkDto dataDefinitionLinkDto) {
        return dataDefinitionService.addLink(dataDefinitionLinkDto);
    }

    /**
     * 移除主数据表和元数据表的关联
     * 
     * @param dataDefinitionLinkDto
     * @return
     */
    @Override
    public boolean removeLink(DataDefinitionLinkDto dataDefinitionLinkDto) {
        return dataDefinitionService.removeLink(dataDefinitionLinkDto);
    }

    /**
     * 获取元数据关联设置
     * 
     * @param mainCollection 主数据表ID
     * @return 元数据关联设置
     */
    @Override
    public List<KnowledgeCollectionVo> getLinks(Long mainCollection) {
        List<Long> metaIds = dataDefinitionService.getLinks(mainCollection);
        List<KnowledgeCollection> knowledgeCollections = knowledgeCollectionService.selectBatchIds(metaIds);
        return knowledgeCollections.stream()
                .map(knowledgeCollection -> HubBeanUtils.convert(knowledgeCollection, KnowledgeCollectionVo.class))
                .collect(Collectors.toList());
    }
}
